import addUserId from "@/utils/addUserId";
import {reqGetUserInfo, reqPostLogin} from "@/api";

const state = {
	tempId: addUserId(),
	token: localStorage.getItem('token3') || '',   // 登录用户的唯一标识初始数据
	userInfo: {nickName: ''}  // 登录用户的初始数据
}
const mutations = {
	SET_TOKEN_STATE(state, payload) {
		state.token = payload.token
	},
	SET_USERINFO_STATE(state, payload) {
		state.userInfo = payload.userInfo
	},
	DELETE_USERINFO_STATE(state) {
		state.userInfo = {nickName: ''}
		state.token = ''
		localStorage.removeItem('token3')
	}
}
const actions = {
	// 1- 登录并获取token
	async getToken({commit}, userInfo) {
		// 用户登录成功时 会返回token
		try {
			const result = await reqPostLogin(userInfo)
			localStorage.setItem('token3', result.token)
			commit('SET_TOKEN_STATE', {token: result.token})
		} catch (e) {
			return Promise.reject({message: e.message})
		}
	},
	// 2- 根据token获取用户信息
	async getUserInfo({commit}) {
		try {
			const result = await reqGetUserInfo()
			commit('SET_USERINFO_STATE', {userInfo: result})
		} catch (e) {
			return Promise.reject({message: e.message})
		}
	},
	// 3- 删除所有的登录用户数据
	async deleteUserInfo({commit}) {
		commit('DELETE_USERINFO_STATE')
	}
}
export default {
	namespaced: true,
	state,
	mutations,
	actions
}